import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
print(sys.path)

from AppDB import AppDB
from AppStoreConnect import *
from io import StringIO
import pandas as pd
from datetime import datetime, timedelta


if __name__ == "__main__":

    start_date = datetime(2024, 5, 12)
    end_date = datetime(2024, 5, 27)

    appDB = AppDB()

    current_date = start_date
    while current_date <= end_date:
        current_date_str = current_date.strftime('%Y-%m-%d')
        
        asc = AppStoreConnectAPI(api_key_path="./AuthKey_sales_and_report_key_S6BQ948292.p8", api_issuer_id="69a6de81-f534-47e3-e053-5b8c7c11a4d1", api_key_id="S6BQ948292")

        print('Getting subscription event report for', current_date_str)
        report = asc.get_sales_report(vendor_id='92612851', report_date=current_date_str, frequency = Frequency.daily, report_type=ReportType.subscription_event, report_sub_type=ReportSubType.summary, version='1_4')
        
        if report is not None:
            df = pd.read_csv(StringIO(report.read().decode('utf-8')), delimiter='\t')

            data_list = df.to_dict('records')

            # Insert data into the table
            appDB.add_subscription_event_report( report_date=current_date, report = data_list)
            
        # Move to the next day
        current_date += timedelta(days=1)
